package assistant

import (
	"context"

	"paper-pro/app/assistant/api/internal/svc"
	"paper-pro/app/assistant/api/internal/types"
	"paper-pro/pkg/ctxdata"
	assistantclient "paper-pro/pkg/rpc/assistant"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// update assistant
func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateLogic) Update(req *types.UpdateAssistantInfo) (resp *types.AssistantMeta, err error) {
	var assistantInfo assistantclient.AssistantInfo
	err = copier.CopyWithOption(&assistantInfo, req, copier.Option{DeepCopy: true})
	if err != nil {
		return nil, errors.Wrapf(err, "Update Assistant数据转换失败，error: %v", err)
	}
	userId, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(err, "Update Assistant: get UserId error: %v", err)
	}
	rpcReq := assistantclient.UpdateAssistantReq{
		AssistantInfo: &assistantInfo,
	}
	rpcReq.IsCreate = false
	rpcReq.AssistantInfo.UserId = userId
	rpcReq.AssistantInfo.Id = req.Id
	rpcReq.AssistantInfo.CreateAt = 0
	rpcReq.AssistantInfo.UpdateAt = 0
	rpcReq.AssistantInfo.LastUseAt = 0

	rpcResp, err := l.svcCtx.AssistantRpc.UpdateAssistant(l.ctx, &rpcReq)
	if err != nil {
		return nil, errors.Wrapf(err, "Update Assistant: AssistantRpc UpdateAssistant error: %v", err)
	}

	return &types.AssistantMeta{
		Id:        rpcResp.AssistantMeta.Id,
		Name:      rpcResp.AssistantMeta.Name,
		LastUseAt: rpcResp.AssistantMeta.LastUseAt,
	}, nil
}
